#include "mprpcapplication.h"
#include <iostream>
#include <string>
#include <unistd.h>

MprpcConfig MprpcApplication::m_config;

void ShowArgsHelp() {
    std::cout << "format: command -i <configfile>" << std::endl;
}

void MprpcApplication::Init(int argc, char* argv[]) {
    if (argc < 3) {
        ShowArgsHelp();
        exit(EXIT_FAILURE);
    }

    std::string config_file;
    // 遍历命令行参数（argv[0]是程序名，从argv[1]开始解析）
    for (int i = 1; i < argc; ++i) {
        std::string arg = argv[i];
        // 检查是否是"-i"选项
        if (arg == "-i") {
            // 确保"-i"后面有参数（即i+1 < argc）
            if (i + 1 >= argc) {
                std::cout << "-i option requires a config file path!" << std::endl;
                ShowArgsHelp();
                exit(EXIT_FAILURE);
            }
            // 保存配置文件路径
            config_file = argv[++i];  // i++跳过下一个参数（已处理）
        } else {
            // 未知选项
            std::cout << "invalid option: " << arg << std::endl;
            ShowArgsHelp();
            exit(EXIT_FAILURE);
        }
    }

    // 此处可添加：检查config_file是否为空（比如用户没传-i的情况）
    if (config_file.empty()) {
        std::cout << "missing -i option!" << std::endl;
        ShowArgsHelp();
        exit(EXIT_FAILURE);
    }

    // 开始加载配置文件 
    m_config.LoadConfigFile(config_file);

    // std::cout << "rpcserverip: " << m_config.Load("rpcserverip") << std::endl;
    // std::cout << "rpcserverport: " << m_config.Load("rpcserverport") << std::endl;
    // std::cout << "zookeeperip: " << m_config.Load("zookeeperip") << std::endl;
    // std::cout << "zookeeperport: " << m_config.Load("zookeeperport") << std::endl;
}

MprpcApplication& MprpcApplication::GetInstance() {
    static MprpcApplication app;
    return app;
}

MprpcConfig& MprpcApplication::GetConfing() {
    return m_config;
}
